<template>
  <div class="app-container" v-loading="loading">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/agents/index' }">智能体</el-breadcrumb-item>
      <el-breadcrumb-item>历史对话</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="main">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="history-left">
            <div class="title">
              <span>{{ form.nickName }}</span>
            </div>
            <div class="list" v-if="messageDevicesList.length > 0">
              <div
                class="item"
                v-for="(item, index) of messageDevicesList"
                :key="index"
                @click="handleGetMessageDevices(item, index)"
                :class="{ on: deviceOnIndex == index }"
              >
                <div class="item-left">
                  <span>{{ item.deviceName }}</span>
                  <div class="dot">{{ item.totalMessage }}</div>
                </div>
                <div class="item-del" @click.stop="handleDeleteDevicesItem(item)">
                  <i class="el-icon-delete-solid"></i>
                </div>
              </div>
            </div>
            <el-empty :image-size="150" description="暂无历史对话" v-else />
          </div>
        </el-col>
        <el-col :span="16">
          <div class="history-right" v-if="deviceOnIndex !== null">
            <div class="title">
              <span>对话详情 - {{ endTime }}</span>
              <span>设备：：{{ deviceId }}</span>
            </div>
            <div class="chart">
              <div
                class="chart-item"
                v-for="(item, index) of messagesInfo.list"
                :key="index"
                :class="{
                  'chart-right': item.sender == 'assistant',
                  'chart-left': item.sender == 'user',
                }"
              >
                <div class="item-main">
                  <div class="item-main-title">
                    <span>{{ item.roleName }}</span>
                    <span>{{ item.createTime }}</span>
                  </div>
                  <div class="item-main-content">
                    <div class="txt">{{ item.message }}</div>
                    <div class="icon" v-if="item.sender !== 'user'">
                      <i class="el-icon-headset" @click="hanldeSound(item)"></i>
                      <i class="el-icon-download" @click="hanldeDown(item)"></i>
                    </div>
                    <div class="tips" v-else>以上内容由 {{ item.sender }} 生成</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="history-right" v-else>
            <el-empty description="请选择一个对话"></el-empty>
          </div>
        </el-col>
      </el-row>
    </div>
    <!--  底部  -->
    <detault-footer />
  </div>
</template>

<script>
import {
  messageDeviceList,
  messageList,
  agentsById,
  testVoice,
  deleteMessage,
} from "@/api/login";
export default {
  data() {
    return {
      loading: false,
      roleId: null,
      messageDevicesList: [],
      form: {},
      deviceOnIndex: null,
      messagesInfo: {},
      endTime: null,
      deviceId: null,
    };
  },
  created() {
    this.roleId = this.$route.query.roleId;
    this.getRoles();
  },
  methods: {
    async getRoles() {
      try {
        this.loading = true;
        const { roleId } = this;
        const [agents, messageDevices] = await Promise.all([
          agentsById(roleId),
          messageDeviceList(roleId),
        ]);
        this.messageDevicesList = messageDevices.data || [];
        this.form = agents.data || {};
      } catch (error) {
        console.error("获取接口错误", error);
      } finally {
        this.loading = false;
      }
    },
    async handleDeleteDevicesItem(item) {
      try {
        const { deviceId } = item;
        const flag = await this.$modal.confirm("是否确认删除该数据项？");
        if (!flag) return;
        await deleteMessage({ deviceId });
        this.deviceOnIndex = null;
        this.getRoles();
        this.$modal.msgSuccess("操作成功");
      } catch (error) {
        console.error("操作失败", error);
      }
    },
    async handleGetMessageDevices(item, index) {
      try {
        const { deviceId } = item;
        const { data } = await messageList(deviceId);
        this.messagesInfo = data;
        this.deviceOnIndex = index;
        this.endTime = data.list[data.list.length - 1].createTime || "";
        this.deviceId = data.list[0].deviceId || "";
      } catch (error) {
        console.error("操作失败", error);
      }
    },
    async hanldeSound(item) {
      let src = "http://192.168.0.110:8091/" + item.audioPath.replace(/\\/g, "/");
      var audioContext = new (window.AudioContext || window.webkitAudioContext)();
      var audioBuffer; // 用于存储音频数据
      var source; // 用于播放音频的节点
      fetch(src) // 使用fetch API获取音频数据流（需要CORS支持或者本地文件）
        .then((response) => response.arrayBuffer())
        .then((arrayBuffer) => audioContext.decodeAudioData(arrayBuffer))
        .then((decodedData) => {
          audioBuffer = decodedData;
          source = audioContext.createBufferSource(); // 创建一个音频源节点
          source.buffer = audioBuffer; // 设置音频源的buffer属性为解码后的音频数据
          source.connect(audioContext.destination); // 将音频源连接到音频上下文的输出（扬声器）
          source.start(0); // 播放音频（0表示立即播放）
        })
        .catch((error) => console.error("解码音频数据失败", error));
    },
    async hanldeDown(item) {
      let src = "http://192.168.0.110:8091/" + item.audioPath.replace(/\\/g, "/");
      window.open(src, "_blank");
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-form {
  max-width: 800px;
  margin: 0 auto;
  width: 90%;
}
.card {
  margin: 22px auto;
}

.main {
  max-width: 1200px;
  margin: 22px auto;
  width: 90%;
}
.history-left,
.history-right {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  height: calc(100vh - 250px);
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  border-bottom: solid #ccc 1px;
  min-height: 56px;
  margin-bottom: -1px;
  padding: 0 24px;
  color: rgba(0, 0, 0, 0.88);
  font-weight: 600;
  font-size: 16px;
  background: transparent;
  border-bottom: 1px solid #f0f0f0;
}
.list {
  width: 100%;
  margin-top: 10px;
  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 12px 24px;
    color: rgba(0, 0, 0, 0.88);
    font-size: 14px;
    border-block-end: 1px solid rgba(5, 5, 5, 0.06);
    cursor: pointer;
    .item-left {
      display: flex;
      align-items: center;
      gap: 10px;
      .dot {
        background-color: rgb(153, 153, 153);
        min-width: 20px;
        height: 20px;
        color: #ffffff;
        font-weight: normal;
        font-size: 12px;
        line-height: 20px;
        white-space: nowrap;
        text-align: center;
        border-radius: 10px;
        box-shadow: 0 0 0 1px #ffffff;
      }
    }
    &:last-child {
      border-bottom: none;
    }
    .item-del {
      color: #f00;
      cursor: pointer;
    }
    &.on,
    &:hover {
      background-color: #e6f7ff;
    }
  }
}
.chart {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  height: calc(100% - 56px);
  overflow-y: auto;
  .chart-item {
    display: flex;
    &.chart-right {
      justify-content: flex-end;
      .item-main {
        background-color: #e6f7ff;
        border-radius: 4px;
      }
    }
    &.chart-left {
      justify-content: flex-start;
      .item-main {
        background-color: #f0f2f5;
        border-radius: 4px;
      }
    }
  }
  .item-main {
    padding: 12px;
    border-radius: 12px;
    max-width: 80%;
    width: fit-content;
    min-width: 300px;
    .item-main-title {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      font-size: 12px;
      color: #666;
      margin-bottom: 20px;
    }
    .item-main-content {
      white-space: pre-wrap;
      word-break: break-word;
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      gap: 15px;
      width: 100%;
      .txt {
        color: rgba(0, 0, 0, 0.88);
        font-size: 14px;
        line-height: 1.5714285714285714;
        list-style: none;
        flex: 1;
      }
      .icon {
        display: flex;
        width: 64px;
        align-items: center;
        justify-content: space-between;
        i {
          font-size: 18px;
          color: #1677ff;
          flex: 1;
          cursor: pointer;
        }
      }
    }
  }
}
.tips {
  font-size: 14px;
  line-height: 1.5714285714285714;
  list-style: none;
  width: 100%;
  text-align: right;
  color: #aaa;
  margin-top: 10px;
}
</style>
